package com.surfacing.rcp.model.codec;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;

import com.surfacing.rcp.model.common.AbstractMessage;
import com.surfacing.rcp.model.entity.Doctor;

public class DoctorDecoder implements MessageDecoder {
	@Override
	public AbstractMessage doDecode(XMLEventReader reader)
			throws XMLStreamException {
		// Create a new staff member
		Doctor member = new Doctor();

		// parse and set up the object
		while (reader.hasNext()) {
			// the type of the event
			XMLEvent event = reader.nextEvent();
			if (event.isStartElement()) {
				String startName = event.asStartElement().getName()
						.getLocalPart();
				// create a new item
				if (Doctor.ID.equalsIgnoreCase(startName))
					member = new Doctor();

				// get the type of the element and set the corresponding value
				if ("doctorId".equalsIgnoreCase(startName))
					member.setId(Integer.valueOf(reader.getElementText()));
				if ("lastName".equalsIgnoreCase(startName))
					member.setLastName(reader.getElementText());
				if ("firstName".equalsIgnoreCase(startName))
					member.setFirstName(reader.getElementText());
			}
			// check for the end element, and return the object
			if (event.isEndElement()) {
				// get the name
				String endElement = event.asEndElement().getName()
						.getLocalPart();
				// check if we have reached the end
				if (Doctor.ID.equalsIgnoreCase(endElement))
					return member;
			}
		}
		return null;
	}
}
